package com.itboye.jigongbao.activity

import `in`.srain.cube.views.ptr.PtrFrameLayout
import `in`.srain.cube.views.ptr.PtrHandler2
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.text.Html
import android.util.Log
import android.view.View
import android.widget.*
import com.itboye.jigongbao.R
import com.itboye.jigongbao.adpapter.JiGongBillsListAdapter
import com.itboye.jigongbao.app.MyApplication
import com.itboye.jigongbao.base.BaseActivity
import com.itboye.jigongbao.bean.FinanceBillBean
import com.itboye.jigongbao.bean.JiYiBiBean
import com.itboye.jigongbao.bean.WorkerBean
import com.itboye.jigongbao.enums.DetailEnums
import com.itboye.jigongbao.retrofit.base.ResultEntity
import com.itboye.jigongbao.retrofit.presenter.UserPrestener
import com.itboye.jigongbao.utils.ByTimeUtils.getDays
import com.itboye.jigongbao.utils.ByTimeUtils.timeFormat
import com.itboye.jigongbao.utils.Const
import com.itboye.jigongbao.utils.Const.Companion.pageSize
import com.itboye.jigongbao.utils.HtmlTextUtil
import com.itboye.jigongbao.utils.SPUtils
import com.itboye.jigongbao.utils.TitleBarUtils
import com.itboye.jigongbao.utils.ToastUtil.ByAlert
import com.itboye.jigongbao.widget.BasePtr
import com.itboye.jigongbao.widget.MyDatePickerDialog
import kotlinx.android.synthetic.main.activity_ji_gong_bills.*
import java.io.Serializable
import java.util.*
import kotlin.collections.ArrayList


/**
 * 记工清单
 */
class JiGongBillsActivity : BaseActivity(), Observer {
    var ar: ArrayList<JiYiBiBean.JiYiBiEntity>? = null


    var txt_date: TextView? = null
    var txt_date_select: TextView? = null
    var txt_name_select: TextView? = null
    var txt_month: TextView? = null
    var arWorkerBean: ArrayList<WorkerBean>? = null
    var financeBean: FinanceBillBean? = null

    var year = ""
    var month = ""
    var day = ""
    override fun update(p0: Observable?, p1: Any?) {
        var entity: ResultEntity = p1 as ResultEntity
        ptr_jigongbills_list_framelayout.refreshComplete()
        ByAlert.alert(entity.msg)
        if (entity.code != 0) {

        } else {
            when (entity.eventType) {
                UserPrestener.By_JgbFinanceBill_overseer_Success -> {
                    financeBean = entity.data as FinanceBillBean
                    setForcemanFinanceBills()
                }
                UserPrestener.By_JgbFinanceBill_overseer_Fail -> {

                }
                UserPrestener.By_JgbFinanceBill_worker_Success -> {
                    financeBean = entity.data as FinanceBillBean
                    setWorkerFinanceBills()
                }
                UserPrestener.By_JgbFinanceBill_worker_Fail -> {

                }
                UserPrestener.By_JgbRecord_queryWorker_Success -> {
                    var jiyiBiBean = entity.data as JiYiBiBean
                    setDataChanged(jiyiBiBean)
                }
                UserPrestener.By_JgbRecord_queryWorker_Fail -> {

                }
                UserPrestener.By_JgbRecord_queryOverseer_Success -> {
                    var jiyiBiBean = entity.data as JiYiBiBean
                    setDataChanged(jiyiBiBean)
                }
                UserPrestener.By_JgbRecord_queryOverseer_Fail -> {

                }
                UserPrestener.By_JgbRecord_queryAllWorkerName_Success -> {
                    arWorkerBean = entity.data as ArrayList<WorkerBean>

                    arWorkerBean!!.add(0, WorkerBean("全部"))
                }
                UserPrestener.By_JgbRecord_queryAllWorkerName_Fail -> {

                }
                else -> {
                }
            }

        }

    }

    private fun setDataChanged(bean: JiYiBiBean) {
        if (pageIndex == 1) {
            ar!!.clear()
        }
        ar!!.addAll(bean.list)
        jiGongAdapter!!.notifyDataSetChanged()
    }

    private fun initAdapter() {
        if (ar == null) {
            ar = ArrayList()
        }
        jiGongAdapter = JiGongBillsListAdapter(this, ar!!, R.layout.item_jigongbills)
        jiGongAdapter!!.activity = JiGongBillsActivity@ this
        list_jigongqingdan!!.adapter = jiGongAdapter
    }


    //工人
    var tv_total_money: TextView? = null//总金额
    var tv_total_yingshou_money: TextView? = null//应收总和
    var tv_total_jiezhi_money: TextView? = null//借支总额
    var tv_total_jiesuan_money: TextView? = null//总结算总额
    var tv_month_money: TextView? = null//本月结余
    var tv_month_yingshou_money: TextView? = null//本月应收
    var tv_month_jiezhi_money: TextView? = null//借支金额
    var tv_month_jiesuan_money: TextView? = null//月结算总额
    //工人账务统计
    private fun setWorkerFinanceBills() {
        var value = String.format("%.2f", financeBean!!.total.debt.toDouble() / 100)
        var startPo = 0
        var endPo = value.length
        var title1 = "<font color='" + resources.getColor(R.color.main_blue) + "'>$value<br/>总金额</font>"
        HtmlTextUtil.setDifferentSizeForTextView2(startPo, endPo, title1, tv_total_money!!)
        tv_total_yingshou_money!!.setText("应收总和：" + String.format("%.2f", financeBean!!.total.income.toDouble() / 100))
        tv_total_jiezhi_money!!.setText("借支总额：" + String.format("%.2f", financeBean!!.total.pre_borrow.toDouble() / 100))
        tv_total_jiesuan_money!!.setText("结算总额：" + String.format("%.2f", financeBean!!.total.settlement.toDouble() / 100))


        value = String.format("%.2f", financeBean!!.monthly.debt.toDouble() / 100)
        startPo = 0
        endPo = value.length
        title1 = "<font color='" + resources.getColor(R.color.main_blue) + "'>$value<br/>本月结余</font>"
        HtmlTextUtil.setDifferentSizeForTextView2(startPo, endPo, title1, tv_month_money!!)
        tv_month_yingshou_money!!.setText("本月应收：" + String.format("%.2f", financeBean!!.monthly.income.toDouble() / 100))
        tv_month_jiezhi_money!!.setText("借支金额：" + String.format("%.2f", financeBean!!.monthly.pre_borrow.toDouble() / 100))
        tv_month_jiesuan_money!!.setText("结算金额：" + String.format("%.2f", financeBean!!.monthly.settlement.toDouble() / 100))
    }

    //工头
    var txt_haixu_pay: TextView? = null //还需支付
    var tv_yingshou_zonghe: TextView? = null//本月应收
    var tv_jiezhi_zonge: TextView? = null//应收金额
    var tv_jiesuan_zonge: TextView? = null//工头结算总额
    //工头账务统计
    private fun setForcemanFinanceBills() {
        var value1 = String.format("%.2f", financeBean!!.total.debt.toDouble() / 100)
        var value2 = "还需支付"
        var startPo = value2.length
        var endPo = (value1 + value2).length + 1
        var title1 = "$value2<font color='" + resources.getColor(R.color.main_blue) + "'><br/>$value1</font>"
        HtmlTextUtil.setDifferentSizeForTextView2(startPo, endPo, title1, txt_haixu_pay!!)
//        txt_haixu_pay!!.setText("还需支付：" + financeBean!!.total.debt.toDouble() / 100)
        tv_yingshou_zonghe!!.setText(Html.fromHtml("应收总和<br/>" + String.format("%.2f", financeBean!!.total.expenditure.toDouble() / 100)))
        tv_jiezhi_zonge!!.setText(Html.fromHtml("借支总额<br/>" + String.format("%.2f", financeBean!!.total.pre_borrow.toDouble() / 100)))
        tv_jiesuan_zonge!!.setText(Html.fromHtml("结算总额<br/>" + String.format("%.2f", financeBean!!.total.settlement.toDouble() / 100)))
    }

    var list_jigongqingdan: ListView? = null
    var iv_actionbar_left: ImageView? = null
    var li_gongren: LinearLayout? = null
    var li_gongtou: LinearLayout? = null
    var jiGongAdapter: JiGongBillsListAdapter? = null
    var alertDialog: AlertDialog? = null

    var userPrestener: UserPrestener? = null
    var role = ""
    var date = ""
    var name: String? = null
    override fun getLayoutId(): Int {
        return R.layout.activity_ji_gong_bills
    }

    var isAtTop = true
    var isAtBottom = false
    override fun initData() {
        TitleBarUtils().initTitlebarStyle1(this, this!!.trans_action_bar_jigongbills!!, "记工清单", R.drawable.img_back, "", 0, "")

        role = SPUtils.getSp(Const.ROLE).toString()
        when (role) {
            Const.WORKER -> {
                txt_date_select!!.visibility = View.GONE
                txt_name_select!!.visibility = View.GONE
            }
            Const.FORCEMAN -> {
                txt_date_select!!.visibility = View.VISIBLE
                txt_name_select!!.visibility = View.VISIBLE
            }
        }
        initAdapter()
        userPrestener = UserPrestener(this)
        date = timeFormat("yyyyMM", System.currentTimeMillis())
        year = timeFormat("yyyy", System.currentTimeMillis())
        month = timeFormat("MM", System.currentTimeMillis())
        day = timeFormat("dd", System.currentTimeMillis())
        query(name, date)

        //两种身份
        setIdentity(intent.getStringExtra("type"))
        list_jigongqingdan!!.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, i, l ->
            var intent = Intent(this, HeZhangDetailActivity::class.java)
            intent.putExtra("title", "明细")
            intent.putExtra("model", ar!![i] as Serializable)
            when (ar!![i].item_type_key) {
                "00S002003" -> {
                    intent.putExtra("type", if (role.equals(Const.FORCEMAN)) {
                        DetailEnums.YIJIBI_FOREMAN_DIANGONG
                    } else {
                        DetailEnums.YIJIBI_WORKER_DIANGONG
                    })
                }
                "00S002002" -> {
                    intent.putExtra("type", if (role.equals(Const.FORCEMAN)) {
                        DetailEnums.YIJIBI_FOREMAN_BAOGONG
                    } else {

                        DetailEnums.YIJIBI_WORKER_BAOGONG
                    })
                }
                "00S002004" -> {
                    intent.putExtra("type", if (role.equals(Const.FORCEMAN)) {
                        DetailEnums.YIJIBI_FOREMAN_JIEZHI
                    } else {

                        DetailEnums.YIJIBI_WORKER_JIEZHI
                    })
                }
                "00S002005" -> {
                    intent.putExtra("type", if (role.equals(Const.FORCEMAN)) {
                        DetailEnums.YIJIBI_FOREMAN_JIESUAN
                    } else {

                        DetailEnums.YIJIBI_WORKER_JIESUAN
                    })
                }
                else -> {
                }
            }
            startActivity(intent)
        }
        userPrestener!!.By_JgbRecord_queryAllWorkerName(MyApplication.instance!!.loginInfo!!.getUid().toString(), this)
        BasePtr.setPagedPtrStyle(ptr_jigongbills_list_framelayout)
        ptr_jigongbills_list_framelayout.setPtrHandler(object : PtrHandler2 {
            override fun onRefreshBegin(frame: PtrFrameLayout?) {
                pageIndex = 1
                query(name, date)
            }

            override fun onLoadMoreBegin(frame: PtrFrameLayout?) {
                pageIndex++
                query(name, date)
            }

            override fun checkCanDoRefresh(frame: PtrFrameLayout?, content: View?, header: View?): Boolean {
                return isAtTop
            }

            override fun checkCanDoLoadMore(frame: PtrFrameLayout?, content: View?, footer: View?): Boolean {
//                list_jigongqingdan.getChildAt()
                return isAtBottom
            }

        })

        list_jigongqingdan!!.setOnScrollListener(object : AbsListView.OnScrollListener {
            override fun onScroll(p0: AbsListView?, p1: Int, p2: Int, p3: Int) {
                if (p1 == 0) {
                    var firstVisibleItemView = list_jigongqingdan!!.getChildAt(0)
                    if (firstVisibleItemView != null && firstVisibleItemView.getTop() == 0) {
                        Log.d("ListView", "##### 滚动到顶部 #####")
                        isAtTop = true
                        isAtBottom = false
                    } else {
                        isAtTop = false
                    }
                } else if ((p1 + p2) == p3) {
                    var lastVisibleItemView = list_jigongqingdan!!.getChildAt(list_jigongqingdan!!.getChildCount() - 1);
                    if (lastVisibleItemView != null && lastVisibleItemView.getBottom() == list_jigongqingdan!!.getHeight()) {
                        Log.d("ListView", "##### 滚动到底部 ######")
                        isAtBottom = true
                        isAtTop = false
                    } else {
                        isAtBottom = false
                    }
                }
            }

            override fun onScrollStateChanged(p0: AbsListView?, p1: Int) {
            }

        })
    }

    var pageIndex: Int = 1
    fun query(name: String?, date: String) {
        txt_date!!.setText("${year}年${month}月")
        var role = SPUtils.getSp(Const.ROLE) as String
        when (role) {
            Const.WORKER -> {
                userPrestener!!.By_JgbRecord_queryWorker(name, null, MyApplication.instance!!.loginInfo!!.getMobile(), date, pageIndex, pageSize, this)
            }
            Const.FORCEMAN -> {
                userPrestener!!.By_JgbRecord_queryOverseer(name, null, MyApplication.instance!!.loginInfo!!.getMobile(), date, pageIndex, pageSize, this)
            }
        }
    }

    private fun setIdentity(type: String) {
        when (type) {
            "0" -> {
                //工人
                li_gongren!!.visibility = (View.VISIBLE)
                li_gongtou!!.visibility = (View.GONE)
                userPrestener!!.By_JgbFinanceBill_worker(MyApplication.instance!!.loginInfo!!.getMobile(), null, null)
            }
            "1" -> {
                //工头
                li_gongren!!.visibility = (View.GONE)
                li_gongtou!!.visibility = (View.VISIBLE)
                userPrestener!!.By_JgbFinanceBill_overseer(MyApplication.instance!!.loginInfo!!.getMobile(), null, null)
            }
            else -> {
            }
        }

    }

    override fun onClick(p0: View?) {
        var intent: Intent? = null
        when (p0!!.id) {
            R.id.iv_actionbar_left -> {
                finish()
            }
            R.id.txt_mingxi -> {
                alertDialog = AlertDialog.Builder(this, R.style.AlertDialog).create()
                var view = View.inflate(this, R.layout.popup_jigongbills_detail, null)
                alertDialog!!.setView(view)
                alertDialog!!.show()
                var txt_work_times: TextView = view.findViewById(R.id.txt_work_times)
                var txt_work_things: TextView = view.findViewById(R.id.txt_work_things)
                txt_work_times.setOnClickListener(this)
                txt_work_things.setOnClickListener(this)
            }
            R.id.txt_work_times -> {
                alertDialog!!.dismiss()
                intent = Intent(this, HeZhangDetailActivity::class.java)
                intent.putExtra("title", "工时明细")
                startActivity(intent)
            }
            R.id.txt_work_things -> {
                alertDialog!!.dismiss()
                intent = Intent(this, HeZhangDetailActivity::class.java)
                intent.putExtra("title", "工事明细")
                startActivity(intent)
            }
            R.id.txt_date_select -> {
                //选择其他日期
//                showDatePickDlg(true, true, false)
                showWorkName(true)
            }
            R.id.txt_month -> {
                //选择其他月份（包含年）
                showDatePickDlg(false, false, true)
            }
            R.id.txt_name_select -> {
                showWorkName(false)
            }
            else -> {
            }
        }
    }

    private fun showWorkName(isDate: Boolean) {
        if (arWorkerBean == null) {
            arWorkerBean = ArrayList()
        }
        var items = Array<String>(arWorkerBean!!.size) { ("").toString() }
        if (isDate) {
            var arDate = getDays(year.toInt(), month.toInt())
            items = Array<String>(arDate!!.size) { ("").toString() }
            arDate!!.forEachIndexed { index, date ->
                items[index] = date
            }
        } else {
            if (arWorkerBean != null) {
                arWorkerBean!!.forEachIndexed { index, workerBean ->
                    items[index] = workerBean.worker_name
                }
            }
        }
        val builder = AlertDialog.Builder(this, 3)
        builder.setItems(items as Array<out String>, object : DialogInterface.OnClickListener {
            override fun onClick(dialog: DialogInterface, which: Int) {
                dialog.dismiss()
                if (isDate) {
                    if (which == 0) {
                        day = ""
                    } else {
                        day = items[which]
                    }
                    txt_date_select!!.setText(items[which])
                } else {
                    if (which == 0) {
                        name = null
                    } else {
                        name = items[which]
                    }
                    txt_name_select!!.setText(items[which])
                }
                this@JiGongBillsActivity.date = "${this@JiGongBillsActivity.year}${this@JiGongBillsActivity.month}${this@JiGongBillsActivity.day}"
                query(name, "${this@JiGongBillsActivity.year}${this@JiGongBillsActivity.month}${this@JiGongBillsActivity.day}")
            }
        })
        builder.create().show()

    }


    protected fun showDatePickDlg(isHideYear: Boolean, isHIdeMonth: Boolean, isHideDay: Boolean) {
        val calendar = Calendar.getInstance()
        val datePickerDialog = MyDatePickerDialog(this@JiGongBillsActivity, object : MyDatePickerDialog.OnDateSetListener {
            override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int, dayOfMonth: Int) {
                if (isHideDay) {
                    this@JiGongBillsActivity.year = year.toString()
                    if (monthOfYear < 10) {
                        this@JiGongBillsActivity.month = "0" + (monthOfYear + 1).toString()
                    } else {

                        this@JiGongBillsActivity.month = (monthOfYear + 1).toString()
                    }
                } else {
                    if (dayOfMonth < 10) {
                        this@JiGongBillsActivity.day = "0" + dayOfMonth.toString()
                    } else {
                        this@JiGongBillsActivity.day = dayOfMonth.toString()
                    }
                    txt_date_select!!.setText(day)
                }
                this@JiGongBillsActivity.date = "${this@JiGongBillsActivity.year}${this@JiGongBillsActivity.month}${this@JiGongBillsActivity.day}"
                query(name, this@JiGongBillsActivity.date)
                Log.v(Const.TAG_DEBUG, date)
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), isHideYear, isHIdeMonth, isHideDay)
        datePickerDialog.show()

    }
}
